<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="com.google.common.collect.Lists" %>
<%@ page import="com.mashape.unirest.http.Unirest" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.concurrent.ForkJoinPool" %>
<%@ page import="java.util.concurrent.ForkJoinTask" %>
<%@ page import="java.util.concurrent.RecursiveAction" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%--
  Created by IntelliJ IDEA.
  User: fangzhou.peng
  Date: 2017/9/12
  Time: 17:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%!
    public static class Task extends RecursiveAction {

        JSONObject map;
        String host;
        List<String> resources;

        Task(JSONObject map, String host, List<String> resources) {
            this.map = map;
            this.host = host;
            this.resources = resources;
        }

        @Override
        protected void compute() {
            if (resources.size() == 1) {
                String resource = resources.get(0);
                try {
                    String resp = Unirest.post(host + resource).asString().getBody();
                    System.out.println(resp);
                    JSONObject json = JSONObject.parseObject(resp);
                    String key = resource.replace("/qatool/", "").replace(".jsp", "");
                    map.put(key, json.getJSONObject("detail"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //System.out.println(resource);
            } else {
                int size = resources.size();
                Task task1 = new Task(map, host, resources.subList(0, size - 1));
                Task task2 = new Task(map, host, resources.subList(size - 1, size));
                invokeAll(task1, task2);
                task1.join();
                task2.join();
            }
        }
    }
%>

<%
    //取出qatool下所有资源
    Set<String> resources = application.getResourcePaths("/qatool");
    System.out.println(resources);

    //去除本身和非jsp的
    Iterator<String> it = resources.iterator();
    while (it.hasNext()) {
        String s = it.next();
        if (!s.endsWith(".jsp") || s.equals("/qatool/qa_tool.jsp")) {
            it.remove();
        }
    }
    System.out.println(resources);

    //forkJoin访问，合成
    String host = request.getLocalAddr() + ":" + request.getLocalPort();
    host = "http://127.0.0.1:8080" + application.getContextPath();
    JSONObject map = new JSONObject();

    ForkJoinPool fjp = new ForkJoinPool(10);
    ForkJoinTask task = new Task(map, host, Lists.newArrayList(resources));
    fjp.invoke(task);

    //返回所有信息
    response.setContentType("application/json;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    out.print(map.toString());
%>